/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufba.lasid.v1.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.thrift.TSerializer;

/**
 *
 * @author Felipe Oliveira Gutierrez
 */
public class PublishVMMetricObservation {

	private static final String EXCHANGE_NAME = "vm_metric";
	private static final String EXCHANGE_TYPE = "topic";

	/**
	 * 
	 * Exemplo de Uso:
	 * 
	 * sh run-publisher.sh
	 * br.ufba.lasid.v2.msgqueue.PublishVMMetricObservation
	 * i-JRH5GY73 "cpuUsage:0.35|memUsage:0.48|diskUsage:0.65"
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		// Create an instance of our Domain object.
		// Keep in mind this is a Thrift generated bean.
		Date date = new Date();
		DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT,
				new Locale("pt,br"));
		Item item = new Item("1", df.format(date), date.getTime(), "metadata",
				EXCHANGE_NAME);

		// obtém uma conexão para acesso ao servidor AMQP
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(AMQPProperties.get(AMQPProperties.HOST));
		factory.setPort(Integer.parseInt(AMQPProperties
				.get(AMQPProperties.PORT)));
		Connection connection = factory.newConnection();

		// obtém um canal, uma forma de multiplexar uma mesma conexão
		Channel channel = connection.createChannel();

		// channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
		channel.queueDeclare(EXCHANGE_NAME, false, false, false, null);

		// Create a new instance of the Thrift Serializer
		TSerializer serializer = new TSerializer();

		// Serialize our domain object to a byte array
		byte[] payload = serializer.serialize(item);

		// Do this 10 times
		for (int i = 0; i < 10; i++) {

			// Publish message on the queue using our domain
			// object as the message (or payload)
			channel.basicPublish("", EXCHANGE_NAME, null, payload);

			// Print a friendly message
			System.out.println(" [x] Sent '" + item.toString() + "'");
		}

		// String routingKey = args[0];
		// String message = args[1];
		//
		// channel.basicPublish(EXCHANGE_NAME, routingKey, null,
		// message.getBytes());
		// System.out.println(" [x] Sent observation for '" + routingKey + "':'"
		// + message + "'");

		channel.close();
		connection.close();
	}
}
